import { createStore, applyMiddleware } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import thunkMiddleware from 'redux-thunk'
import storage from 'redux-persist/lib/storage/session'
import rootReducer from './modules/reducer'

const persistConfig = {
    key: 'root',
    storage: storage,
    whitelist: ['auth']
};

const persistedReducer = persistReducer(persistConfig, rootReducer);
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(createStore);
/**
 * 创建store
 * @param  {[type]} initialState [description]
 * @return {[type]}              [description]
 */
export default function configureStore(initialState) {
    // console.log('initialState', initialState);
    // const store = createStore(rootReducer, initialState)
    const store = createStoreWithMiddleware(persistedReducer, initialState, 
        // 使用Redux DevTools浏览器插件调试redux
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

    //热加载,及时跟新reducer
    if (module.hot) {
        // Enable Webpack hot module replacement for reducers
        module.hot.accept('./modules/reducer', () => {
            const nextReducer = require('./modules/reducer');
            store.replaceReducer(nextReducer);
        });
    }
    let persistor = persistStore(store);

    return { store, persistor };
}
